import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:magma/storylines/home_story/rank_list_story.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';

/// 打卡页面视图模型
class CheckInNavigatorViewModel extends BaseViewModel {
  DateTime _currentMonth = DateTime.now();
  DateTime get currentMonth => _currentMonth;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化数据
  void setupData() {
    notifyListeners();
  }

  /// 切换关注状态
  Future<bool> toggleFollowStatus(String targetUserId) async {
    if (!isLoggedIn) {
      return false;
    }

    final isFollowing = appState.followManager.isFollowing(
      currentUser!.id,
      targetUserId,
    );

    if (isFollowing) {
      final result = await appState.followManager.terminateFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      return result;
    } else {
      final result = await appState.followManager.establishFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      return result;
    }
  }

  /// 检查是否已关注用户
  bool checkFollowingStatus(String targetUserId) {
    if (!isLoggedIn) return false;
    return appState.followManager.isFollowing(currentUser!.id, targetUserId);
  }

  /// 切换到上个月
  void navigateToPreviousMonth() {
    _currentMonth = DateTime(_currentMonth.year, _currentMonth.month - 1);
    notifyListeners();
  }

  /// 切换到下个月
  void navigateToNextMonth() {
    _currentMonth = DateTime(_currentMonth.year, _currentMonth.month + 1);
    notifyListeners();
  }

  /// 获取当前月份的所有日期
  List<DayRecordItem> retrieveMonthDays() {
    final firstDayOfMonth = DateTime(
      _currentMonth.year,
      _currentMonth.month,
      1,
    );
    final lastDayOfMonth = DateTime(
      _currentMonth.year,
      _currentMonth.month + 1,
      0,
    );

    List<DayRecordItem> days = [];

    // 添加月初的空白天数
    int firstWeekday = firstDayOfMonth.weekday;
    if (firstWeekday < 7) {
      for (int i = 0; i < firstWeekday; i++) {
        days.add(
          DayRecordItem(date: null, isToday: false, checkinStatus: null),
        );
      }
    }

    // 添加月份的所有日期
    for (int day = 1; day <= lastDayOfMonth.day; day++) {
      final date = DateTime(_currentMonth.year, _currentMonth.month, day);
      final today = DateTime.now();
      final isToday =
          date.year == today.year &&
          date.month == today.month &&
          date.day == today.day;

      bool? checkinStatus;
      if (isLoggedIn) {
        checkinStatus = appState.checkinTracker.getUserCheckinStatus(
          currentUser!.id,
          date,
        );
      }

      days.add(
        DayRecordItem(
          date: date,
          isToday: isToday,
          checkinStatus: checkinStatus,
        ),
      );
    }

    return days;
  }

  /// 执行打卡
  Future<bool> performCheckin() async {
    final result = await appState.checkinTracker.executeCheckin(
      currentUser!.id,
    );
    if (result) {
      notifyListeners();
      return true;
    } else {
      setError(
        appState.checkinTracker.modelError?.message ?? 'Check-in failed',
      );
      return false;
    }
  }

  /// 检查今天是否已打卡
  bool hasCheckedInToday() {
    if (!isLoggedIn) return false;
    return appState.checkinTracker.hasUserCheckedInToday(currentUser!.id);
  }

  /// 获取推荐用户列表（随机，排除当前用户）
  List<UserModel> fetchRecommendedUsers() {
    final allUsers = appState.userStore.getAllUsers();
    final filteredUsers =
        allUsers.where((user) {
          return currentUser == null || user.id != currentUser!.id;
        }).toList();

    // 打乱顺序
    filteredUsers.shuffle();

    // 返回前8个
    return filteredUsers.take(8).toList();
  }

  /// 根据ID获取用户
  UserModel? retrieveUser(String userId) {
    return appState.userStore.getUserById(userId);
  }
}

/// 日期记录项
class DayRecordItem {
  final DateTime? date;
  final bool isToday;
  final bool? checkinStatus; // true: 已打卡, false: 未打卡, null: 无记录

  DayRecordItem({
    required this.date,
    required this.isToday,
    required this.checkinStatus,
  });
}

/// 打卡页面
class CheckInStory extends StatefulWidget {
  const CheckInStory({super.key});

  @override
  State<CheckInStory> createState() => _CheckInStoryState();
}

class _CheckInStoryState extends State<CheckInStory>
    with RouteAware, WidgetsBindingObserver {
  CheckInNavigatorViewModel? _viewModel;
  RouteObserver<ModalRoute<dynamic>>? _routeObserver;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 订阅路由变化
    final route = ModalRoute.of(context);
    if (route != null && route is PageRoute) {
      _routeObserver = RouteObserver<ModalRoute<dynamic>>();
      _routeObserver!.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    _routeObserver?.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    // 从其他页面返回到当前页面时触发
    super.didPopNext();
    if (_viewModel != null) {
      _viewModel!.setupData();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用恢复到前台时刷新数据
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.setupData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<CheckInNavigatorViewModel>.reactive(
      viewModelBuilder: () => CheckInNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
        viewModel.setupData();
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: SafeArea(
            child: Column(
              children: [
                // 顶部标题栏
                _constructTopBar(context),

                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 描述文字
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: Text(
                            'Complete daily basic training tasks to better prepare for the marathon.',
                            textAlign: TextAlign.center,
                          ).blackHanSans(
                            fontSize: 16.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w400,
                          ),
                        ),

                        SizedBox(height: 16.h),

                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: SizedBox(
                            width: double.infinity,
                            height: 1.h,
                            child: CustomPaint(painter: DashedLinePainter()),
                          ),
                        ),

                        SizedBox(height: 20.h),

                        // 日历容器
                        _constructCalendarContainer(viewModel),

                        SizedBox(height: 30.h),

                        // Training partners 标题
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: Text('Training partners').blackHanSans(
                            fontSize: 24.sp,
                            color: MagmaColor.white,
                          ),
                        ),

                        SizedBox(height: 16.h),

                        // 推荐用户列表
                        _constructRecommendedUsersList(viewModel),

                        SizedBox(height: 30.h),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部标题栏
  Widget _constructTopBar(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              MagmaConstant.back,
              width: 24.w,
              height: 24.w,
              color: MagmaColor.white,
            ),
          ),
          SizedBox(width: 16.w),
          Text(
            'Daily Training Check-In',
          ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
        ],
      ),
    );
  }

  /// 构建日历容器
  Widget _constructCalendarContainer(CheckInNavigatorViewModel viewModel) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: MagmaColor.black,
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: MagmaColor.white, width: 1.w),
      ),
      child: Column(
        children: [
          // 月份切换器
          _assembleMonthSwitcher(viewModel),

          SizedBox(height: 20.h),

          // 星期标题
          _assembleWeekdayHeaders(),

          SizedBox(height: 12.h),

          // 日期网格
          _assembleDaysGrid(viewModel),

          SizedBox(height: 24.h),

          // 打卡按钮
          _assembleCheckinButton(viewModel),
        ],
      ),
    );
  }

  /// 组装月份切换器
  Widget _assembleMonthSwitcher(CheckInNavigatorViewModel viewModel) {
    final monthNames = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          onTap: viewModel.navigateToPreviousMonth,
          child: Icon(Icons.chevron_left, color: MagmaColor.white, size: 28.w),
        ),
        Text(
          '${monthNames[viewModel.currentMonth.month - 1]} ${viewModel.currentMonth.year}',
          style: TextStyle(
            height: 1.4,
            fontSize: 14.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w400,
            fontFamily:
                GoogleFonts.protestStrike(
                  fontWeight: FontWeight.w400,
                ).fontFamily,
          ),
        ),
        GestureDetector(
          onTap: viewModel.navigateToNextMonth,
          child: Icon(Icons.chevron_right, color: MagmaColor.white, size: 28.w),
        ),
      ],
    );
  }

  /// 组装星期标题
  Widget _assembleWeekdayHeaders() {
    const weekdays = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children:
          weekdays.map((day) {
            return Expanded(
              child: Center(
                child: Text(
                  day,
                  style: TextStyle(
                    fontSize: 11.sp,
                    color: MagmaColor.white,
                    fontFamily:
                        GoogleFonts.protestStrike(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            );
          }).toList(),
    );
  }

  /// 组装日期网格
  Widget _assembleDaysGrid(CheckInNavigatorViewModel viewModel) {
    final days = viewModel.retrieveMonthDays();

    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 7,
        mainAxisSpacing: 8.h,
        crossAxisSpacing: 8.w,
        childAspectRatio: 1,
      ),
      itemCount: days.length,
      itemBuilder: (context, index) {
        final dayItem = days[index];
        return _assembleDayCell(dayItem);
      },
    );
  }

  /// 组装单个日期单元格
  Widget _assembleDayCell(DayRecordItem dayItem) {
    if (dayItem.date == null) {
      return SizedBox();
    }

    Color backgroundColor = Colors.transparent;
    Color textColor = MagmaColor.white;
    Widget? icon;

    if (dayItem.isToday) {
      backgroundColor = MagmaColor.black;
    }

    // 只有已打卡的日期才显示图标，未打卡的只显示日期
    if (dayItem.checkinStatus == true) {
      icon = Image.asset(MagmaConstant.check, width: 20.w, height: 20.w);
    }

    return Container(
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: MagmaColor.white.withValues(alpha: 0.3),
          width: 1.w,
        ),
      ),
      child: Center(
        child:
            icon ??
            Text(
              dayItem.date!.day.toString(),
              style: TextStyle(
                fontSize: 16.sp,
                color: textColor,
                fontFamily:
                    GoogleFonts.racingSansOne(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                fontWeight: FontWeight.w400,
              ),
            ),
      ),
    );
  }

  /// 组装打卡按钮
  Widget _assembleCheckinButton(CheckInNavigatorViewModel viewModel) {
    final hasChecked = viewModel.hasCheckedInToday();

    return Builder(
      builder: (context) {
        return GestureDetector(
          onTap:
              hasChecked
                  ? null
                  : () async {
                    // 检查是否登录
                    if (!viewModel.isLoggedIn) {
                      await LoginRequiredDialog.show(context);
                      return;
                    }

                    // 执行打卡
                    final result = await viewModel.performCheckin();
                    if (context.mounted) {
                      if (result) {
                        MagmaToast.success(
                          context,
                          title: 'Check-in successful!',
                        );
                      } else {
                        MagmaToast.error(
                          context,
                          title: viewModel.modelError ?? 'Check-in failed',
                        );
                      }
                    }
                  },
          child: Container(
            width: double.infinity,
            height: 50.h,
            decoration: BoxDecoration(
              color: hasChecked ? MagmaColor.grey : MagmaColor.purple,
              borderRadius: BorderRadius.circular(25.r),
            ),
            child: Center(
              child: Text(
                hasChecked ? 'Checked In' : 'Check-In',
              ).blackHanSans(fontSize: 18.sp, color: MagmaColor.black),
            ),
          ),
        );
      },
    );
  }

  /// 构建推荐用户列表
  Widget _constructRecommendedUsersList(CheckInNavigatorViewModel viewModel) {
    final users = viewModel.fetchRecommendedUsers();

    return SizedBox(
      height: 108.h,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return _constructUserCard(user, viewModel);
        },
      ),
    );
  }

  /// 构建用户卡片
  Widget _constructUserCard(
    UserModel user,
    CheckInNavigatorViewModel viewModel,
  ) {
    return StatefulBuilder(
      builder: (context, setState) {
        final isFollowing = viewModel.checkFollowingStatus(user.id);

        return MagmaTap(
          onTap: () {
            // 跳转到用户主页
            QR.to(MagmaRouter.otherUserPath.replaceAll(':userId', user.id));
          },
          child: Container(
            width: 82.w,
            margin: EdgeInsets.only(right: 12.w),
            decoration: BoxDecoration(
              color: MagmaColor.black,
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: MagmaColor.white, width: 1.w),
            ),
            child: AspectRatio(
              aspectRatio: 82 / 108,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Spacer(),
                  // 用户头像和关注按钮（叠加）
                  SizedBox(
                    width: 58.w,
                    height: 68.w,
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        // 用户头像
                        Positioned(
                          top: 0,
                          left: 0,
                          right: 0,
                          child: Container(
                            width: 58.w,
                            height: 58.w,
                            decoration: BoxDecoration(shape: BoxShape.circle),
                            child: ClipOval(
                              child: Image.asset(
                                user.avatar,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        ),

                        // 关注按钮（叠加在头像下边框上）
                        Positioned(
                          bottom: 0,
                          left: 0,
                          right: 0,
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              // 检查是否登录
                              if (!viewModel.isLoggedIn) {
                                await LoginRequiredDialog.show(context);
                                return;
                              }

                              // 保存当前关注状态，用于显示正确的提示信息
                              final wasFollowing = isFollowing;

                              // 切换关注状态
                              final result = await viewModel.toggleFollowStatus(
                                user.id,
                              );

                              if (context.mounted && result) {
                                // 局部刷新当前卡片
                                setState(() {});

                                // 显示成功提示（使用操作前的状态）
                                MagmaToast.success(
                                  context,
                                  title:
                                      wasFollowing ? 'Unfollowed' : 'Followed',
                                );
                              }
                            },
                            child: Container(
                              width: 20.w,
                              height: 20.w,
                              decoration: BoxDecoration(
                                color: MagmaColor.white,
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: MagmaColor.black,
                                  width: 2.w,
                                ),
                              ),
                              child: Center(
                                child: Icon(
                                  isFollowing ? Icons.check : Icons.add,
                                  size: 14.w,
                                  color: MagmaColor.black,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  Spacer(),

                  // 用户名
                  Text(
                    user.username,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ).inter(
                    fontSize: 15.sp,
                    color: MagmaColor.white,
                    fontWeight: FontWeight.w500,
                  ),
                  Spacer(),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
